package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;

public class RegUsersDemo {
    public static void main(String[] args) {
        try {
            int t = 0;
            Random random = new Random();
            while (t < 10) {
                t++;
                //随机生成一个姓名
                String name_a = "刘孙桂周王张李";
                String name_b = "宇轩晨涵睿博欣诺泽航强伟杰军峰毅超刚明辉婷娜琳妍琪梦雪悦婉馨德礼仁义信谦诚智勇贤沐语然熙若沁翊曈珩柠";
                String username = "";
                username += name_a.charAt(random.nextInt(name_a.length()));
                int r = random.nextInt(2) + 1;
                for (int i = 0; i < r; i++) {
                    username += name_b.charAt(random.nextInt(name_b.length()));
                }
                String password = "";
                for (int i = 0; i < 6; i++) {
                    password += (int) (Math.random() * 10);
                }
                //随机生成昵称
                String nickname = "小" + name_a.charAt(random.nextInt(name_a.length()));
                //随机生成年龄
                int age = (int) (Math.random() * 100);

                //数据库链接
                Class.forName("com.mysql.cj.jdbc.Driver");
                Connection connection = DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/tedu?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true",
                        "root", "root");
                Statement statement = connection.createStatement();
                //录入数据库
                String sql="INSERT INTO userinfo(username,password,nickname,age) VALUES('"+username+"','"+password+"','"+nickname+"',"+age+")";
                int num = statement.executeUpdate(sql);
                System.out.println(num>0?"添加成功":"添加失败");
                connection.close();
            }
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
